<!-- LineChart.vue -->
<template>
    <canvas ref="chartCanvas"></canvas>
</template>

<script setup>
import { ref, onMounted, onUpdated, onBeforeUnmount } from 'vue';
import Chart from 'chart/auto';

const props = defineProps({
    data: {
        type: Object,
        required: true
    }
});

const chartCanvas = ref(null);
let chartInstance = null;

function initChart() {
    if (chartInstance) {
        chartInstance.destroy();
    }

    const ctx = chartCanvas.value.getContext('2d');
    chartInstance = new Chart(ctx, {
        type: 'line',
        data: props.data,
        options: {
            responsive: true,
            maintainAspectRatio: true, // 改为 true，保持宽高比
            aspectRatio: 2, // 可选：设置宽高比，例如宽是高的两倍
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
}
onMounted(() => {
    initChart();
});

onUpdated(() => {
    initChart();
});

onBeforeUnmount(() => {
    if (chartInstance) {
        chartInstance.destroy();
    }
});
</script>